package com.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 栅栏
 *
 */
@Slf4j
public class CyclicBarrierExample {
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);//当5个线程到达屏障时往下执行

    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();

        for (int i = 0; i < 10; i++) {
            final int threadNum = i;
            Thread.sleep(1000);//各个线程执行间隔一秒，使效果更明显。
            executorService.execute(()->{
                try{
                    doSth(threadNum);
                }catch (InterruptedException e){
                    throw new RuntimeException(e);
                }
            });
        }
        executorService.shutdown();
    }

    public static void doSth(int threadNum) throws InterruptedException{
        Thread.sleep(100);//模拟某项操作
        log.info("线程到达屏障,线程：{}",threadNum);
        try{
            cyclicBarrier.await();
        }catch (Exception e){
            log.warn("cyclicBarrierExeception:",e);
        }
        log.info("线程执行完毕，线程：{}", threadNum);
    }
}
